import { Injectable } from '@angular/core';
import { Observable, Observer, Subject, throwError } from 'rxjs';
import { catchError, finalize, tap } from 'rxjs/operators';
import { ToastService } from '../toast.service';
import { OutlayService } from '../outlay.service';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { OutlayModifyComponent } from 'src/app/pages/dashboard/components/outlay-modify/outlay-modify.component';
import { Outlay } from 'src/app/models/outlay';
import { TranslateService } from '@ngx-translate/core';
import * as moment from 'moment';

interface ModifyOption {
  title: string,
  data?: Outlay
}

@Injectable({
  providedIn: 'root'
})
export class OutlayActionService {

  constructor(
    private toast: ToastService,
    private outlayService: OutlayService,
    private modalService: NzModalService,
    private translate: TranslateService,
  ) { }

  name = '支出记录';

  modify(option: ModifyOption): Observable<any> {
    return new Observable(observer => {
      const aModalRef: NzModalRef = this.modalService.create({
        nzTitle: this.translate.instant(option.title),
        nzContent: OutlayModifyComponent,
        nzComponentParams: { aValue: option.data },
        nzCancelText: this.translate.instant('outlay.modify.cancel'),
        nzOkText: this.translate.instant('outlay.modify.save'),
        nzOnOk: (instance) => {
          instance.verify();
          if (instance.validateForm.invalid) {
            return false;
          }
          const values = instance.validateForm.value;
          aModalRef.updateConfig({ nzOkLoading: true });
          const params: any = {
            ...values,
            time: moment(values.time).format('YYYY-MM-DD')
          };
          let apiAction = this.outlayService.save(params), tip = 'outlay.api_save_success';
          if (option.data && option.data.id) {
            params.id = option.data.id;
            apiAction = this.outlayService.update(params);
            tip = 'outlay.api_modify_success';
          }
          apiAction.pipe(
            tap(res => {
              if (res.code === 200) {
                observer.next();
                observer.complete();
                aModalRef.destroy();
                this.toast.success(tip, '', { name: this.name });
              }
            }),
            finalize(() => {
              aModalRef.updateConfig({ nzOkLoading: false });
            })
          ).subscribe();
          return false;
        }
      });
    });
  }

  delete(id: string): Observable<any> {
    return new Observable(observer => {
      const aModalRef = this.modalService.confirm({
        nzTitle: this.translate.instant('outlay.delete.title'),
        nzCancelText: this.translate.instant('outlay.delete.cancel'),
        nzOkText: this.translate.instant('outlay.delete.ok'),
        nzOnOk: () => {
          aModalRef.updateConfig({ nzOkLoading: true });
          this.outlayService.delete({ id }).pipe(
            tap(res => {
              if (res.code === 200) {
                observer.next();
                observer.complete();
                aModalRef.destroy();
                this.toast.success('outlay.api_delete_success');
              }
            }),
            finalize(() => {
              aModalRef.updateConfig({ nzOkLoading: false });
            })
          ).subscribe();
          return false;
        }
      });
    });
  }

}
